<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>WebSocket 群聊室</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        h1 {
            color: #333;
            text-align: center;
        }
        
        .connection-panel {
            margin-bottom: 20px;
            padding: 15px;
            background: #f0f8ff;
            border-radius: 5px;
        }
        
        .input-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        
        #messages {
            height: 300px;
            border: 1px solid #ddd;
            padding: 10px;
            overflow-y: auto;
            margin-bottom: 15px;
            background: white;
            border-radius: 4px;
        }
        
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 4px;
        }
        
        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }
        
        .avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
            background-color: #ccc;
            overflow: hidden;
        }
        
        .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .username {
            font-weight: bold;
        }
        
        .timestamp {
            font-size: 0.8em;
            color: #666;
            margin-left: auto;
        }
        
        .system-message {
            background-color: #e6f7ff;
            color: #0066cc;
        }
        
        .user-message {
            background-color: #e6ffe6;
            border-left: 3px solid #4CAF50;
        }
        
        .other-message {
            background-color: #f9f9f9;
            border-left: 3px solid #cccccc;
        }
        
        .status {
            font-style: italic;
            color: #666;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>WebSocket 群聊室</h1>

        <div class="connection-panel">
            <div class="input-group">
                <label for="userId">用户ID:</label>
                <input type="text" id="userId" placeholder="输入用户ID" value="user001">
            </div>
            <div class="input-group">
                <label for="userName">用户名:</label>
                <input type="text" id="userName" placeholder="输入用户名" value="用户1">
            </div>
            <div class="input-group">
                <label for="userAvatar">头像URL:</label>
                <input type="text" id="userAvatar" placeholder="输入头像URL" value="http://s.yun-live.com/images/20200602/287c910edbf90aa11f909a93d964a244.png">
            </div>
            <div class="input-group">
                <label for="groupId">群组ID:</label>
                <input type="text" id="groupId" placeholder="输入群组ID" value="group1">
            </div>
            <button id="connectBtn">连接</button>
            <button id="disconnectBtn" disabled>断开连接</button>
            <div id="connectionStatus" class="status">未连接</div>
        </div>

        <div id="messages"></div>

        <div class="input-group">
            <label for="messageInput">消息内容:</label>
            <input type="text" id="messageInput" placeholder="输入消息内容..." disabled>
            <button id="sendBtn" disabled>发送</button>
        </div>
    </div>

    <script>
        // 全局变量
        let socket = null;
        let currentUser = {
            id: null,
            name: null,
            avatar: null
        };
        let currentGroupId = null;

        // DOM元素
        const userIdInput = document.getElementById('userId');
        const userNameInput = document.getElementById('userName');
        const userAvatarInput = document.getElementById('userAvatar');
        const groupIdInput = document.getElementById('groupId');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const messagesDiv = document.getElementById('messages');
        const connectionStatus = document.getElementById('connectionStatus');

        // 连接WebSocket
        function connectWebSocket() {
            currentUser.id = userIdInput.value.trim();
            currentUser.name = userNameInput.value.trim();
            currentUser.avatar = userAvatarInput.value.trim();
            currentGroupId = groupIdInput.value.trim();

            if (!currentUser.id || !currentUser.name || !currentGroupId) {
                appendSystemMessage('请输入用户ID、用户名和群组ID');
                return;
            }

            // 构建WebSocket URL (适配您的后端接口)
            const wsUrl = `http://yws.yunxianchang.com/ws/group?group_id=${encodeURIComponent(currentGroupId)}&user_id=${encodeURIComponent(currentUser.id)}&name=${encodeURIComponent(currentUser.name)}&avatar=${encodeURIComponent(currentUser.avatar)}`;

            // 创建WebSocket连接
            socket = new WebSocket(wsUrl);

            // 连接成功回调
            socket.onopen = function() {
                updateUI(true);
                appendSystemMessage(`已连接到群组: ${currentGroupId}`);
            };

            // 接收消息回调
            socket.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    const timestamp = new Date(data.timestamp).toLocaleTimeString();

                    if (data.event === 'system') {
                        appendSystemMessage(data.content, timestamp);
                    } else if (data.sender_id === currentUser.id) {
                        appendUserMessage(data.content, timestamp);
                    } else {
                        appendOtherMessage(data.sender, data.avatar, data.content, timestamp);
                    }
                } catch (e) {
                    appendSystemMessage(`收到消息: ${event.data}`);
                }
            };

            // 连接关闭回调
            socket.onclose = function() {
                updateUI(false);
                appendSystemMessage('连接已关闭');
            };

            // 错误处理
            socket.onerror = function(error) {
                appendSystemMessage(`连接错误: ${error.message}`);
                updateUI(false);
            };
        }

        // 断开WebSocket连接
        function disconnectWebSocket() {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.close();
            }
            updateUI(false);
        }

        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || !socket || socket.readyState !== WebSocket.OPEN) return;

            const msg = {
                event: "message",
                group_id: currentGroupId,
                content: message
            };
            console.log("Sending message: ", JSON.stringify(msg))
            socket.send(JSON.stringify(msg));
            appendUserMessage(message, new Date().toLocaleTimeString());
            messageInput.value = '';
        }

        // 更新UI状态
        function updateUI(connected) {
            if (connected) {
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                messageInput.disabled = false;
                sendBtn.disabled = false;
                connectionStatus.textContent = `已连接 (群组: ${currentGroupId})`;
                connectionStatus.style.color = 'green';
            } else {
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                messageInput.disabled = true;
                sendBtn.disabled = true;
                connectionStatus.textContent = '未连接';
                connectionStatus.style.color = 'red';
                socket = null;
            }
        }

        // 添加系统消息
        function appendSystemMessage(message, timestamp = new Date().toLocaleTimeString()) {
            const div = document.createElement('div');
            div.className = 'message system-message';
            div.innerHTML = `
                <div class="message-header">
                    <span>系统消息</span>
                    <span class="timestamp">${timestamp}</span>
                </div>
                <div>${message}</div>
            `;
            messagesDiv.appendChild(div);
            scrollToBottom();
        }

        // 添加用户消息
        function appendUserMessage(message, timestamp) {
            const div = document.createElement('div');
            div.className = 'message user-message';
            div.innerHTML = `
                <div class="message-header">
                    <div class="avatar">
                        <img src="${currentUser.avatar}" alt="${currentUser.name}">
                    </div>
                    <span class="username">我</span>
                    <span class="timestamp">${timestamp}</span>
                </div>
                <div>${message}</div>
            `;
            messagesDiv.appendChild(div);
            scrollToBottom();
        }

        // 添加其他用户消息
        function appendOtherMessage(username, avatar, message, timestamp) {
            const div = document.createElement('div');
            div.className = 'message other-message';
            div.innerHTML = `
                <div class="message-header">
                    <div class="avatar">
                        <img src="${avatar || 'https://via.placeholder.com/30'}" alt="${username}">
                    </div>
                    <span class="username">${username}</span>
                    <span class="timestamp">${timestamp}</span>
                </div>
                <div>${message}</div>
            `;
            messagesDiv.appendChild(div);
            scrollToBottom();
        }

        // 滚动到底部
        function scrollToBottom() {
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 事件监听
        connectBtn.addEventListener('click', connectWebSocket);
        disconnectBtn.addEventListener('click', disconnectWebSocket);
        sendBtn.addEventListener('click', sendMessage);

        // 按Enter键发送消息
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 初始化
        appendSystemMessage('请输入用户信息和群组ID，然后点击"连接"按钮');
    </script>
</body>

</html>